var express = require('express');
var router = express.Router();
const usersService = require("../service/userService");
const { sha256, secretKey } = require('../utils/token');
const jwt = require("jsonwebtoken");
var fetch = require('node-fetch');
const https = require("https");
const { v4: uuidv4 } = require('uuid');
const { base64_decode } = require('../utils/file');
const httpsAgent = new https.Agent({ rejectUnauthorized: false });

const APP_ID = "wx457004f898a98ca0";
const SECRET = "0dc55cff45d36b3f4f3f21cf2b90ccbb";

// 微信小程序登录
router.get('/weixinLogin', async function (req, res) {
  let code = req.query.code;
  // console.log(code);
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APP_ID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
  // console.log("url", url);
  try {
    let fetchResult = await fetch(url, {
      agent: httpsAgent
    });
    let data = await fetchResult.json();
    // console.log('usersData', url, data)
    if (!data.errcode) {
      let user = await usersService.usernameExist(data.openid);
      // console.log("suers", user);
      if (Object.keys(user).length > 0) {
        // console.log("user", user);
        let token = jwt.sign({ data: user }, secretKey);
        res.send({
          data: user,
          token
        });
      } else {
        let newUser = await usersService.insert({ openid: data.openid, pwd: '' });
        let token = jwt.sign({ data: newUser }, secretKey);
        // console.log("newUser", newUser);
        res.send({
          data: newUser,
          token
        });
      }
    } else {
      res.send({});
    }
  } catch (e) {
    // console.log("error:", e);
    res.send({});
  }

});
// 修改
router.post('/weixinDetail/:id', async function (req, res) {
  console.log("req", req.body);
  let id = req.params.id;
  console.log("id", id);
  let { nickname, avatar, phone, gender, addr, password } = req.body;
  console.log("添加用户数据id", id);

  let user = await usersService.findById(id);
  if (avatar) {
    let strUUID = uuidv4();
    base64_decode(avatar, "./public/images/" + strUUID + ".jpeg");
    user.avatar = strUUID + ".jpeg";
  }
  if (nickname) {
    user.nickname = nickname;
  }
  if (password) {
    user.password = password;
  }
  if (phone) {
    user.phone = phone;
  }
  if (addr) {
    user.addr = addr;
  }
  if (gender) {
    user.gender = gender;
  }
  await usersService.update(user);
  res.send(user);
})

/**
 * @swagger
 * /users:
 *    get:
 *      tags:
 *      - users
 *      summary: 获取用户分页
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
//分页查询
router.get('/', async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchObj = {};
  if (type) {
    searchObj[type] = { $regex: value };
  }
  // console.log("user",searchObj);
  let data = await usersService.find(searchObj,
    { current: current || 1, pageSize: pageSize || 5 });
  // console.log(data);
  res.send({ data });
});



/**
 * @swagger
 * /users/all:
 *    get:
 *      tags:
 *      - users
 *      summary: 获取用户全部
 *      responses:
 *        200:
 *          description: 操作成功
 *        401:
 *          description: 权限不足
 * */
// 查询所有
router.get("/all", async function (req, res) {
  let data = await usersService.findAll();
  res.send({ data });
})


//删除
router.delete("/:id", async function (req, res) {
  let { id } = req.params;
  let data = await usersService.remove(id);
  res.send({ data });
});
//搜索
router.get('/', async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchObj = {};
  if (type) {
    searchObj[type] = { $regex: value };
  }
  let data = await usersService.find(searchObj,
    { current: current || 1, pageSize: pageSize || 5 });
  // console.log(data);
  res.send({ data });
});
//id查询
router.get("/:id", async function (req, res) {
  let { id } = req.params;
  let data = await usersService.findById(id);
  res.send({ data });
});
//修改冻结
router.put("/frozen/:id", async function (req, res) {
  let id = req.params.id;
  let { state } = req.body;
  let user = await usersService.findById(id);
  console.log("frozen", state);
  console.log("frozen", user);
  console.log("frozen", user.state);
  if (state == "true") {
    user.state = "false";
  }
  if (state == "false") {
    user.state = "true"
  }
  console.log(111, user);
  await usersService.update(user);
  res.send(user);
});



module.exports = router;
